import { ref, watch } from 'vue'
import router from '@/router'

import { getEffectData } from '@/server/client/api_article'
import {
  deleteArticle,
  updateArticleIsShow,
  searchArticle
} from '@/server/serve/api_article'

import type { ArticleListDataTypes } from '@/server/client/api_article'

import type { FormConfigTypes } from '@/base-ui/form'

import { ElMessageBox, ElMessage } from 'element-plus'

/**
 *
 * @param formConfig 表单配置文件
 * @param articleType 文章类型 0新闻资讯 1公益作用 2公益记录
 * @returns
 */
export default function (formConfig: FormConfigTypes, articleType: number) {
  // 表单数据
  const newFormData: any = {}
  for (const item of formConfig.formItems) {
    newFormData[`${item.field}`] = ''
  }
  const formData = ref(newFormData)

  // 表格数据
  const tableData = ref<any>()

  // 分页数据
  const pageList = ref({
    // 当前分页页数
    currentPage: 1,
    // 当前展示数据条数
    pageSize: 10,
    // 数据总数
    total: 0,
    pageSizes: [5, 10, 15, 20]
  })

  // 监听表格数据展示方式，是否为默认 搜索数据
  const defaultDataShowType = ref<boolean>(true)

  // 数据初始化
  const dataInitialization = () => {
    // 默认数据
    if (defaultDataShowType.value) {
      getEffectData(
        articleType,
        pageList.value.pageSize,
        'true',
        (pageList.value.currentPage - 1) * pageList.value.pageSize
      ).then(({ data: articleList }) => {
        tableData.value = articleList.data?.articleList
        pageList.value.total = articleList.data?.allNums!
      })
    }
    // 搜索数据
    else {
      searchArticle(
        articleType,
        formData.value.name,
        pageList.value.pageSize,
        (pageList.value.currentPage - 1) * pageList.value.pageSize
      ).then(({ data: searchResult }) => {
        tableData.value = searchResult.data?.articleList
        pageList.value.total = searchResult.data?.allNums!
      })
    }
  }

  // 监听分页切换
  watch(
    pageList,
    () => {
      dataInitialization()
    },
    { immediate: true }
  )

  // 切换是否展示
  /**
   *
   * @param articleID 文章ID
   */
  const handleChange = async (item: ArticleListDataTypes) => {
    const { _id, isShow } = item
    const { data: changeResult } = await updateArticleIsShow(_id)

    if (changeResult.code) {
      item.isShow = !isShow
      return ElMessage({
        type: 'warning',
        message: changeResult.mes
      })
    }
    ElMessage({
      type: 'success',
      message: changeResult.mes
    })
  }

  // 编辑文章
  /**
   *
   * @param articleID 文章ID
   */
  const hanldeRoutr = (articleID: string) => {
    router.push(`/admin/article/${articleID}`)
  }

  // 删除文章
  const handleDelete = (articleID: string) => {
    ElMessageBox.confirm('确认删除该文章吗?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        const { data: deleteResult } = await deleteArticle(articleID)
        if (deleteResult.code)
          return ElMessage({
            type: 'warning',
            message: deleteResult.mes
          })
        dataInitialization()
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
      })
      .catch(() => {
        console.log()
      })
  }

  // 搜索文章
  const handleSearch = async () => {
    defaultDataShowType.value = false
    dataInitialization()
  }

  // 新增文章
  const handleAdd = () => {
    router.push('/admin/create')
  }

  return {
    formData,
    tableData,
    pageList,
    handleChange,
    hanldeRoutr,
    handleDelete,
    handleSearch,
    handleAdd
  }
}
